package com.quxue.im.ws;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

import static com.quxue.im.common.Const.TOKEN;

/**
 * HttpSessionHandshakeInterceptor 是 Spring WebSocket 框架提供的一个拦截器接口，
 * 用于在 WebSocket 握手过程中进行拦截和处理。
 * 它允许你在 WebSocket 连接建立之前或之后执行一些自定义逻辑。
 */
@Component
public class BootWebSocketInterceptor extends HttpSessionHandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        ServletServerHttpRequest req = (ServletServerHttpRequest)request;

        String token = req.getServletRequest().getParameter("Authorization");
        //将token设置到属性，BootWebSocketHandler 上线方法就可以获取属性
        attributes.put(TOKEN,token);

        return super.beforeHandshake(request, response, wsHandler, attributes);
    }
}
